#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "user_button.h"

#include "driver/gpio.h"
#include "iot_button.h"

#include "user_hid_control.h"

static const char *TAG = "[BUTTON]";

#define BUTTON_START_PIN GPIO_NUM_7
#define BUTTON_ACTIVE_LEVEL     0

const char *button_event_table[] = {
    "BUTTON_PRESS_DOWN",
    "BUTTON_PRESS_UP",
    "BUTTON_PRESS_REPEAT",
    "BUTTON_PRESS_REPEAT_DONE",
    "BUTTON_SINGLE_CLICK",
    "BUTTON_DOUBLE_CLICK",
    "BUTTON_MULTIPLE_CLICK",
    "BUTTON_LONG_PRESS_START",
    "BUTTON_LONG_PRESS_HOLD",
    "BUTTON_LONG_PRESS_UP",
};

void button_start_event_cb(void *arg, void *data)
{
#if CONFIG_GPIO_BUTTON_SUPPORT_POWER_SAVE
    esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
    if (cause != ESP_SLEEP_WAKEUP_UNDEFINED) {
        ESP_LOGI(TAG, "Wake up from light sleep, reason %d", cause);
    }
#endif

switch((button_event_t)data){
case BUTTON_PRESS_DOWN:{    // 按下
    break;
}
case BUTTON_PRESS_UP:{      // 松开
    break;
}
case BUTTON_SINGLE_CLICK:{  // 一次按下
    if(task_is_running()){
        suspend_hid_control();
    } else{
        resume_hid_control();
    }
    break;
}
default: break;
}
}

void button_init()
{
    button_config_t btn_cfg = {
        .type = BUTTON_TYPE_GPIO,
        .gpio_button_config = {
            .gpio_num = BUTTON_START_PIN,
            .active_level = BUTTON_ACTIVE_LEVEL,
#if CONFIG_GPIO_BUTTON_SUPPORT_POWER_SAVE
            .enable_power_save = true,
#endif
        },
    };
    button_handle_t btn_start = iot_button_create(&btn_cfg);
    assert(btn_start);
    esp_err_t err = iot_button_register_cb(btn_start, BUTTON_PRESS_DOWN, button_start_event_cb, (void*)BUTTON_PRESS_DOWN);
    err |= iot_button_register_cb(btn_start, BUTTON_PRESS_UP, button_start_event_cb, (void*)BUTTON_PRESS_UP);
    err |= iot_button_register_cb(btn_start, BUTTON_SINGLE_CLICK, button_start_event_cb, (void*)BUTTON_SINGLE_CLICK);
    ESP_ERROR_CHECK(err);
}
